package com.example.music

import android.animation.ObjectAnimator
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import android.view.View
import android.view.animation.LinearInterpolator
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.example.music.model.Song
import com.example.music.service.MusicService
import java.util.concurrent.TimeUnit

class MusicDetailActivity : AppCompatActivity(), 
    MusicService.OnPlaybackStateChangeListener,
    MainActivity.OnProgressUpdateListener {
    private lateinit var albumCover: ImageView
    private lateinit var songTitleText: TextView
    private lateinit var artistNameText: TextView
    private lateinit var seekBar: SeekBar
    private lateinit var currentTimeText: TextView
    private lateinit var totalTimeText: TextView
    private lateinit var playPauseButton: ImageButton
    private lateinit var prevButton: ImageButton
    private lateinit var nextButton: ImageButton

    private var musicService: MusicService? = null
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as MusicService.MusicBinder
            val musicService = binder.getService()
            this@MusicDetailActivity.musicService = musicService
            musicService.setPlaybackStateChangeListener(this@MusicDetailActivity)
            
            // 同步当前状态.
            val state = musicService.getPlaybackState()
            currentSong = state.first
            updateUI(state.first)
            
            // 立即同步进度条和播放状态
            val duration = musicService.getDuration()
            val position = musicService.getCurrentPosition()
            seekBar.max = duration
            seekBar.progress = position
            updateTimeText(position, duration)
            
            // 同步播放状态
            syncPlaybackState(state.third)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            musicService?.setPlaybackStateChangeListener(null)
            musicService = null
        }
    }

    private var rotationAnimator: ObjectAnimator? = null
    private var currentSongIndex = 0
    private var songs: List<Song> = emptyList()
    private var currentSong: Song? = null

    private val TAG = "MusicDetailActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            setContentView(R.layout.activity_music_detail)

            // 获取传递的数据
            currentSongIndex = intent.getIntExtra("song_index", 0)
            @Suppress("UNCHECKED_CAST")
            songs = intent.getSerializableExtra("songs") as? List<Song> ?: emptyList()

            if (songs.isEmpty()) {
                Toast.makeText(this, "没有可播放的歌曲", Toast.LENGTH_SHORT).show()
                finish()
                return
            }

            initViews()
            setupListeners()
            
            // 先绑定服务
            bindMusicService()
            
            // 注册进度更新监听
            (application as? MyApplication)?.mainActivity?.setProgressUpdateListener(this)
            
            // 初始化当前歌曲
            currentSong = songs[currentSongIndex]
            updateUI(currentSong)
        } catch (e: Exception) {
            Log.e(TAG, "初始化失败", e)
            Toast.makeText(this, "初始化失败: ${e.message}", Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        // 处理新的 Intent
        intent?.let { handleIntent(it) }
    }

    private fun handleIntent(intent: Intent) {
        currentSongIndex = intent.getIntExtra("song_index", 0)
        @Suppress("UNCHECKED_CAST")
        songs = intent.getSerializableExtra("songs") as? List<Song> ?: emptyList()

        if (songs.isEmpty()) {
            Log.e(TAG, "没有可播放的歌曲")
            Toast.makeText(this, "没有可播放的歌曲", Toast.LENGTH_SHORT).show()
            finish()
            return
        }

        if (!::albumCover.isInitialized) {
            initViews()
            setupListeners()
        }

        // 获取当前歌曲并更新UI
        currentSong = songs[currentSongIndex]
        updateUI(currentSong)
        
        // 立即同步进度条和播放状态
        musicService?.let { service ->
            val duration = service.getDuration()
            val position = service.getCurrentPosition()
            seekBar.max = duration
            seekBar.progress = position
            updateTimeText(position, duration)
            
            // 同步播放状态
            syncPlaybackState(service.isPlaying())
        }
    }

    private fun updateUI(song: Song?) {
        song?.let {
            // 更新标题和艺术家
            songTitleText.text = it.name
            it.artist?.let { artist ->
                artistNameText.visibility = View.VISIBLE
                artistNameText.text = artist
            } ?: run {
                artistNameText.visibility = View.GONE
            }

            // 加载封面图片
            it.coverUrl?.let { url ->
                Log.d(TAG, "加载封面图片: $url")
                Glide.with(this)
                    .load(url)
                    .error(R.drawable.ic_error_placeholder)
                    .placeholder(R.drawable.ic_error_placeholder)
                    .into(albumCover)
            } ?: run {
                Log.e(TAG, "封面URL为空")
                albumCover.setImageResource(R.drawable.ic_error_placeholder)
            }
        }
    }

    override fun onBackPressed() {
        // 优雅地处理返回
        try {
            musicService?.stop()
        } catch (e: Exception) {
            Log.e(TAG, "清理资源失败", e)
        }
        super.onBackPressed()
    }

    private fun initViews() {
        albumCover = findViewById(R.id.albumCover)
        songTitleText = findViewById(R.id.songTitle)
        artistNameText = findViewById(R.id.artistName)
        seekBar = findViewById(R.id.seekBar)
        currentTimeText = findViewById(R.id.currentTime)
        totalTimeText = findViewById(R.id.totalTime)
        playPauseButton = findViewById(R.id.playPauseButton)
        prevButton = findViewById(R.id.prevButton)
        nextButton = findViewById(R.id.nextButton)

        // 设置工具栏返回按钮
        findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar).setNavigationOnClickListener {
            finish()
        }
    }

    private fun setupListeners() {
        playPauseButton.setOnClickListener {
            val service = musicService ?: return@setOnClickListener
            if (service.isPlaying()) {
                service.pause()
            } else {
                service.start()
            }
            // 立即更新播放按钮状态
            updatePlayPauseButton(service.isPlaying())
        }

        prevButton.setOnClickListener {
            playPrevious()
        }

        nextButton.setOnClickListener {
            playNext()
        }

        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    musicService?.seekTo(progress)
                    updateTimeText(progress, seekBar?.max ?: 0)
                    // 同步更新底部状态栏的进度
                    (application as? MyApplication)?.mainActivity?.apply {
                        updatePlaybackState()
                    }
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 拖动时暂停进度更新
                (application as? MyApplication)?.mainActivity?.stopProgressUpdate()
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 拖动结束后恢复进度更新
                (application as? MyApplication)?.mainActivity?.startProgressUpdate()
            }
        })
    }

    private fun playSong(song: Song) {
        currentSong = song
        updateUI(song)
        
        musicService?.playSong(song) {
            setupProgressUpdate()
            startRotationAnimation()
            playPauseButton.setImageResource(R.drawable.ic_pause)
        }
    }

    private fun playPrevious() {
        try {
            if (currentSongIndex > 0) {
                currentSongIndex--
                currentSong = songs[currentSongIndex]
                updateUI(currentSong)
                musicService?.playSong(currentSong!!) {
                    playPauseButton.setImageResource(R.drawable.ic_pause)
                    startRotationAnimation()
                    // 同步更新主界面的当前歌曲和状态
                    (application as? MyApplication)?.mainActivity?.apply {
                        updateCurrentSong(currentSong!!, currentSongIndex, songs)
                        updatePlaybackState()
                    }
                }
            } else {
                Toast.makeText(this, "已经是第一首歌", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Log.e(TAG, "播放上一首失败: currentSongIndex=$currentSongIndex", e)
            Toast.makeText(this, "切换失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun playNext() {
        try {
            if (currentSongIndex < songs.size - 1) {
                currentSongIndex++
                currentSong = songs[currentSongIndex]
                updateUI(currentSong)
                musicService?.playSong(currentSong!!) {
                    playPauseButton.setImageResource(R.drawable.ic_pause)
                    startRotationAnimation()
                    // 同步更新主界面的当前歌曲和状态
                    (application as? MyApplication)?.mainActivity?.apply {
                        updateCurrentSong(currentSong!!, currentSongIndex, songs)
                        updatePlaybackState()
                    }
                }
            } else {
                Toast.makeText(this, "已经是最后一首歌", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Log.e(TAG, "播放下一首失败: currentSongIndex=$currentSongIndex", e)
            Toast.makeText(this, "切换失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun startRotationAnimation() {
        val service = musicService ?: return
        try {
            if (service.isPlaying()) {
                rotationAnimator?.cancel()
                rotationAnimator = ObjectAnimator.ofFloat(albumCover, View.ROTATION, 0f, 360f).apply {
                    duration = 20000 // 20秒转一圈
                    repeatCount = ObjectAnimator.INFINITE
                    interpolator = LinearInterpolator()
                    start()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "启动旋转动画失败", e)
        }
    }

    private fun setupProgressUpdate() {
        val service = musicService ?: return
        seekBar.max = service.getDuration()
        updateTimeText(0, service.getDuration())
    }

    private fun updateTimeText(current: Int, total: Int) {
        currentTimeText.text = formatTime(current)
        totalTimeText.text = formatTime(total)
    }

    private fun formatTime(millis: Int): String {
        val minutes = TimeUnit.MILLISECONDS.toMinutes(millis.toLong())
        val seconds = TimeUnit.MILLISECONDS.toSeconds(millis.toLong()) -
                TimeUnit.MINUTES.toSeconds(minutes)
        return String.format("%02d:%02d", minutes, seconds)
    }

    override fun onPause() {
        super.onPause()
        // 暂停旋转动画
        rotationAnimator?.pause()
    }

    override fun onResume() {
        super.onResume()
        // 如果正在播放，恢复旋转动画
        if (musicService?.isPlaying() == true) {
            rotationAnimator?.resume()
        }
    }

    override fun onDestroy() {
        try {
            updateMainActivity()
            musicService?.setPlaybackStateChangeListener(null)
            rotationAnimator?.cancel()
            rotationAnimator = null
            unbindService(serviceConnection)
        } catch (e: Exception) {
            Log.e(TAG, "销毁失败", e)
        }
        super.onDestroy()
    }

    override fun onPlaybackStateChanged(song: Song?, isPlaying: Boolean) {
        runOnUiThread {
            try {
                currentSong = song
                updateUI(song)
                syncPlaybackState(isPlaying)
            } catch (e: Exception) {
                Log.e(TAG, "更新播放状态失败", e)
            }
        }
    }

    private fun bindMusicService() {
        Intent(this, MusicService::class.java).also { intent ->
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
            startService(intent)
        }
    }

    override fun onProgressUpdated(position: Int, duration: Int) {
        runOnUiThread {
            try {
                if (duration > 0) {
                    seekBar.max = duration
                    seekBar.progress = position
                    updateTimeText(position, duration)
                }
            } catch (e: Exception) {
                Log.e(TAG, "更新进度失败", e)
            }
        }
    }

    private fun updatePlayPauseButton(isPlaying: Boolean) {
        playPauseButton.setImageResource(
            if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play
        )
    }

    override fun finish() {
        updateMainActivity()
        super.finish()
    }

    private fun syncPlaybackState(isPlaying: Boolean) {
        updatePlayPauseButton(isPlaying)
        if (isPlaying) {
            startRotationAnimation()
        } else {
            rotationAnimator?.pause()
        }
    }

    private fun updateMainActivity() {
        (application as? MyApplication)?.mainActivity?.apply {
            setProgressUpdateListener(null)
            updatePlaybackState()
            startProgressUpdate()
        }
    }
} 